<?php
/**
 * Created by PhpStorm.
 * User: sunku
 * Date: 2018/1/15
 * Time: 10:23
 * @crontab    0 1 * * * /usr/local/php/bin/php /webwww/weizhi/crontab/run/message/Message.php > /log/crontab/message/Message.log 2>&1 &
 */

require_once __DIR__ . '/../run.php';
class CustomerArchive
{
    private function messageRemind(){
        $customers = $this->getAllCustomer();
        if(is_array($customers) && count($customers)>0){
            foreach ($customers as $customer){
                $userInfo = $this->getUserInfo(['id'=>$customer['admin_id']]);
                if($userInfo){
                    $remaind_time = intval($userInfo['tracking_time']);
                    if($remaind_time>0){
                        $orderInfo = $this->getCustomerOrder([
                            'admin_id'=> $customer['admin_id'],
                            'customer_id'=> $customer['id']
                        ]);
                        $phase_log = $this->getOnePhaseLog([
                            'admin_id'=> $customer['admin_id'],
                            'customer_id'=> $customer['id']
                        ]);
                        $x_time = $customer['create_time'];
                        if(isset($phase_log) && $phase_log){
                            $x_time = $phase_log['create_time'];
                        }
                        $day = self::count_days(time(), $x_time);
                        var_dump('day:'.$day);
                        var_dump('customer:'.$customer['id']);
                        if(isset($day) && ($day<=$remaind_time)){
                            if(!$orderInfo || ($orderInfo['status']!=55)){
                                $data = [];
                                $data['uid'] = $customer['admin_id'];
                                $data['customer_id'] = $customer['id'];
                                $data['message'] = "【跟进提醒】你有一个客户已经{$day}天没有跟新进度了，超时将回收，快去看看吧，客户ID:{$customer['id']} 客户:{$customer['company_name']} 产品:{$customer['product_name']}";
                                $data['status'] = 0;

                                $this->insertMessage($data);
                            }
                        }else{
                            if(!$orderInfo || ($orderInfo['status']!=55)) {
                                //客户归档
                                $sql = "UPDATE `wz_customers` SET `status`= 10,`archive_time`=:archive_time WHERE id=:customer_id LIMIT 1";
                                DB::Query($sql, ['customer_id' => $customer['id'],'archive_time'=>time()]);

                                $data = [];
                                $data['uid'] = $customer['admin_id'];
                                $data['customer_id'] = $customer['id'];
                                $data['message'] = "【归档提醒】你有一个客户已经{$day}天未跟进了，已归档回收，客户:{$customer['company_name']} 推广产品:{$customer['product_name']}";
                                $data['status'] = 0;

                                $this->insertMessage($data);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * @return array|bool
     */
    private function getAllCustomer(){
        $sql = 'SELECT * FROM wz_customers WhERE status = 1 AND phase < 20';
        $result = DB::select($sql);
        if(!$result){
            return [];
        }else{
            return $result;
        }
    }

    /**
     * @param $params
     * @return array|bool
     */
    private function getUserInfo($params){
        $sql = 'SELECT au.*, ug.name AS group_name, ug.id AS group_id,ug.total_enrollment,ug.tracking_time
                    FROM tb_auth_user au 
                    LEFT JOIN tb_auth_user_usergroup as uug ON uug.user_id=au.id 
                    LEFT JOIN tb_auth_user_group as ug ON uug.user_group_id=ug.id
                    WHERE au.id = :uid';
        $result = DB::getOne($sql,['uid'=>$params['id']]);
        if($result!==false){
            return $result;
        }else{
            return false;
        }
    }

    /**
     * @param $params
     * @return bool
     */
    private function insertMessage($params){
        $sql = 'INSERT INTO wz_message 
                  (uid,customer_id,message,status,create_time,update_time) 
                  VALUES (:uid,:customer_id,:message,:status,:create_time,:update_time)';
        $result = DB::insert($sql,[
            'uid' => $params['uid'],
            'customer_id' => $params['customer_id'],
            'message' => $params['message'],
            'status' => $params['status'],
            'create_time' => time(),
            'update_time' => time(),
        ]);
        if($result!==false){
            return $result;
        }else{
            return false;
        }
    }

    /**
     * @param $params
     * @return array|bool
     */
    public function getOnePhaseLog($params){
        $sql = 'SELECT * FROM wz_phase_log WHERE admin_id=:admin_id AND customer_id=:customer_id ORDER BY create_time DESC';
        $result = DB::getOne($sql,[
            'admin_id' => $params['admin_id'],
            'customer_id'=>$params['customer_id']
        ]);
        if($result!==false){
            return $result;
        }else{
            return false;
        }
    }

    /**
     * @param $params
     * @return array|bool
     */
    public function getCustomerOrder($params){
        $sql = 'SELECT id,order_code,status FROM wz_order WHERE admin_id=:admin_id AND customer_id=:customer_id AND status IN (-5,1,5,10,15,20,25,30,35,40,45,50,55)';
        $result = DB::getOne($sql,[
            'admin_id' => $params['admin_id'],
            'customer_id'=>$params['customer_id']
        ]);
        if($result!==false){
            return $result;
        }else{
            return false;
        }
    }
    /**
     * 天数计算
     * @param $a_time
     * @param $b_time
     * @return int
     */
    function count_days($a_time, $b_time){
        $a_dt = getdate($a_time);
        $b_dt = getdate($b_time);
        $a_new = mktime(12, 0, 0, $a_dt['mon'], $a_dt['mday'], $a_dt['year']);
        $b_new = mktime(12, 0, 0, $b_dt['mon'], $b_dt['mday'], $b_dt['year']);
        return intval(abs($a_new-$b_new)/86400);
    }
    /**
     * 脚本入口
     */
    public function run($stat_date) {
        //加载数据库配置
        //DB::cfgFile('local');
        DB::cfgFile('online');

        $this->messageRemind();
    }
}

//启动脚本
$obj = new CustomerArchive();
$obj->run();